package com.unittec.drainage.provider.auth.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.unittec.drainage.provider.auth.entity.SysPermission;
import com.unittec.drainage.provider.auth.entity.SysPermissionDataRule;
import com.unittec.drainage.provider.auth.mapper.SysPermissionDataRuleMapper;
import com.unittec.drainage.provider.auth.mapper.SysPermissionMapper;
import com.unittec.drainage.provider.root.ServiceRoot;
import com.unittec.drainage.provider.utils.query.QueryGenerator;
import com.unittec.drainage.sdk.root.common.CommonConstant;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author Jason
 * @description 菜单数据权限Service
 * @date 2019/11/07
 */
@Service
public class SysPermissionDataRuleService extends ServiceRoot<SysPermissionDataRuleMapper, SysPermissionDataRule> {

    @Resource
    private SysPermissionMapper sysPermissionMapper;

    /**
     * 根据前端传递的权限名称和权限值参数来查询权限数据
     */
    public List<SysPermissionDataRule> queryPermissionRule(SysPermissionDataRule permRule) {
        QueryWrapper<SysPermissionDataRule> queryWrapper = QueryGenerator.initQueryWrapper(permRule, null);
        return this.list(queryWrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    public void savePermissionDataRule(SysPermissionDataRule sysPermissionDataRule) {
        this.save(sysPermissionDataRule);
        SysPermission permission = sysPermissionMapper.selectById(sysPermissionDataRule.getPermissionId());
        boolean flag = permission != null
            && (permission.getRuleFlag() == null || permission.getRuleFlag().equals(CommonConstant.RULE_FLAG_0));
        if (flag) {
            permission.setRuleFlag(CommonConstant.RULE_FLAG_1);
            sysPermissionMapper.updateById(permission);
        }
    }

}
